<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/10
// +----------------------------------------------------------------------

namespace app\erp\model;

use think\Db;
use think\Model;

/**
 * 调拨管理
 * @package app\erp\model
 */
class ErpAllocation extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'xm_erp_goods_allocation';
    protected $table_sku = 'xm_erp_goods_allocation_sku';
    protected $table_num = 'xm_erp_goods_warehouse_stock_num';

    /**
     * 添加数据
     * @param uid=user_id 	            int         操作人
     * @param from_warehouse_id 		int         调出仓
     * @param to_warehouse_id 		    int
     * @param remarks 		            string      备注
     * @param handled_by 		        string      经办人
     * @param code 		                string      调拨单号
     * @param create_time 		        date
     * @param update_time 	            date
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, (int)id)
     */
    public function addData($user_id, $from_warehouse_id, $to_warehouse_id, $remark, $handled_by, $code){
        $data['uid']                = $user_id;
        $data['from_warehouse_id']  = $from_warehouse_id;
        $data['to_warehouse_id']    = $to_warehouse_id;
        $data['remark']             = $remark;
        $data['handled_by']         = $handled_by;
        $data['code']               = $code;
        $res = $this -> isUpdate(false) ->data($data, true) -> save();
        if($res){
            return array_out(200, 'success', $this -> id);
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 编辑数据-出入库状态all_status
     * @param id 		                int      调拨单id
     * @param all_status 		        int      调拨状态 0申请中 1已审核 2已出库 3取消出库 4已入库
     * @param create_time 		        date
     * @param update_time 	            date
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, (int)id)
     */
    public function editDataOutGoing($id,$all_status){
        $map = [];
        $map['id'] = $id;

        $data = [];
        $data['all_status']    = $all_status;
        $data['update_time']   = time();
        $res = $this ->update($data, $map);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 出库单申请通过后更改库存数
     * @param $id
     */
    public function outGoing($id)
    {
		//总库存 	= 总库存   - 实际出库库存	  (调拨申请时总库存没有发生变化)
		//冻结库存 	= 冻结库存 - 调拨申请时的库存 (因为调拨申请时 已冻结库存)
		//可用库存 	= 可用库存 + (调拨申请时的库存 - 实际出库库存) (实际出库会发生变化  调拨申请时已更改可用库存 所以实际出库时要加回来)
        $res = Db::table($this->table_num)
            ->alias('sn')
            ->join($this->table_sku.' sku','sn.sku_id = sku.sku_id')
            ->join($this->table.' sk','sk.id = sku.allocation_id AND sk.from_warehouse_id = sn.warehouse_id')
            ->where('sk.id = '.$id)
            ->update([
                'sn.stock_num'		=>	Db::raw('sn.stock_num-sku.ck_num'),
                'sn.frozen_num'		=>	Db::raw('sn.frozen_num-sku.num'),
                'sn.available_num'	=>	Db::raw('sn.available_num + (sku.num - sku.ck_num)'),
            ]);
		
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }
	
	 /**
     * 编辑数据-调入仓 增加冻结库存
     * @param id 		                int      调拨单id
     * @param all_status 		        int      调拨状态 0申请中 1已审核 2已出库 3取消出库 4已入库
     * @param create_time 		        date
     * @param update_time 	            date
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, (int)id)
     */
    public function frozenGoing($id){
         //联查去差集，num表不存在的仓库规格
        $list = Db::table($this->table)
            ->alias('sk')
            ->join($this->table_sku.' sku','sk.id = sku.allocation_id')
            ->leftJoin($this->table_num.' sn','sku.sku_id = sn.sku_id AND sk.to_warehouse_id = sn.warehouse_id')
            ->where('sn.id is null and sk.id = '.$id)
            ->field('sk.*,sku.*')
            ->select();
        if($list){
            //无数据新增（根据skuid查找规格）
            foreach ($list as $k=>$v){
                //查找表存在规格数据
                $data_num = Db::table($this->table_num)->where('sku_id',$v['sku_id'])->find();
                $data['warehouse_id']       = $v['to_warehouse_id'];
                $data['goods_id']           = $data_num['goods_id'];
                $data['sku_id']             = $v['sku_id'];
                $data['stock_num']          = '0';
                $data['frozen_num']         = '0';
                $data['available_num']      = '0';
                $data['price']              = $data_num['price'];
                $data['create_time']        = time();
                $data['update_time']        = time();

                $res = Db::table($this->table_num)->insert($data);
            }
        }
        $res =  Db::table($this->table)
            ->alias('sk')
            ->join($this->table_sku.' sku','sk.id = sku.allocation_id')
            ->join($this->table_num.' sn','sku.sku_id = sn.sku_id AND sk.to_warehouse_id = sn.warehouse_id')
            ->where('sk.id = '.$id)
            ->update([
                'sn.stock_num'		=>	Db::raw('sn.stock_num+sku.ck_num'),
                'sn.frozen_num'		=>	Db::raw('sn.frozen_num+sku.ck_num'),
            ]);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }
	
	/**
     * 取消出库 增加库存
     * @param $id
     */
    public function cancelGoing($id)
    {
        $res = Db::table($this->table_num)
            ->alias('sn')
            ->join($this->table_sku.' sku','sn.sku_id = sku.sku_id')
            ->join($this->table.' sk','sk.id = sku.allocation_id AND sk.from_warehouse_id = sn.warehouse_id')
            ->where('sk.id = '.$id)
            ->update([
                'sn.frozen_num'		=>	Db::raw('sn.frozen_num - sku.num'),
				'sn.available_num'	=>	Db::raw('sn.available_num + sku.num'),
            ]);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 入库单申请通过后更改库存数
     * @param $id
     */
    public function warehousing($id)
    {
        //联查去差集，num表不存在的仓库规格
        $list = Db::table($this->table)
            ->alias('sk')
            ->join($this->table_sku.' sku','sk.id = sku.allocation_id')
            ->leftJoin($this->table_num.' sn','sku.sku_id = sn.sku_id AND sk.to_warehouse_id = sn.warehouse_id')
            ->where('sn.id is null and sk.id = '.$id)
            ->field('sk.*,sku.*')
            ->select();
        if($list){
            //无数据新增（根据skuid查找规格）
            foreach ($list as $k=>$v){
                //查找表存在规格数据
                $data_num = Db::table($this->table_num)->where('sku_id',$v['sku_id'])->find();
                $data['warehouse_id']       = $v['to_warehouse_id'];
                $data['goods_id']           = $data_num['goods_id'];
                $data['sku_id']             = $v['sku_id'];
                $data['stock_num']          = '0';
                $data['frozen_num']         = '0';
                $data['available_num']      = '0';
                $data['price']              = $data_num['price'];
                $data['create_time']        = time();
                $data['update_time']        = time();

                $res = Db::table($this->table_num)->insert($data);
            }
        }
        $res =  Db::table($this->table)
            ->alias('sk')
            ->join($this->table_sku.' sku','sk.id = sku.allocation_id')
            ->join($this->table_num.' sn','sku.sku_id = sn.sku_id AND sk.to_warehouse_id = sn.warehouse_id')
            ->where('sk.id = '.$id)
            ->update([
                'sn.stock_num'		=>	Db::raw('sn.stock_num-(sku.ck_num-sku.rk_num)'),
                'sn.frozen_num'		=>	Db::raw('sn.frozen_num-sku.ck_num'),
                'sn.available_num'	=>	Db::raw('sn.available_num+sku.rk_num'),
            ]);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

}
